package com.fs.util;

import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by fengshuai on 17/6/16.
 */
public class SqlUtil {

    /**
     * 如果传入参数对应的value不存在，则会返回where("1=1"),表示忽略此参数的过滤
     *
     * @param params       参数MAP
     * @param paramKey     参数名称
     * @param fieldInTable 参数对应的值，要匹配的数据库字段
     * @param haveToExist  表示fieldInTable在查询时是否必须有值，如果必须有值，但paramKey对应的value为空，则返回where("1=0")
     */
    public static String preparedInSql(Map<String, Object> params, String paramKey, String fieldInTable, boolean haveToExist) {

        StringBuffer whereSql = new StringBuffer();


        List valueList = params.containsKey(paramKey) ? (List) params.get(paramKey) : null;

        if (CollectionUtils.isEmpty(valueList)) {
            if (haveToExist) {
                whereSql.append("1=0");
            } else {
                whereSql.append("1=1");
            }

        } else {
            whereSql.append(fieldInTable + " in (");
            for (int i = 0, size = valueList.size(); i < size; i++) {
                if (i == 0) {
                    whereSql.append("#{" + paramKey + "[" + i + "]}");
                } else {
                    whereSql.append(",").append("#{" + paramKey + "[" + i + "]}");
                }
            }
            whereSql.append(")");
        }

        return whereSql.toString();
    }


    public static String preparedInSql(Map<String, Object> params, String paramKey, String fieldInTable) {
        return preparedInSql(params, paramKey, fieldInTable, false);
    }
}
